package com.wugenqiang.common.interceptor;


import com.wugenqiang.common.enums.Types;
import com.wugenqiang.constant.ParamConstant;
import com.wugenqiang.project.system.pojo.User;
import com.wugenqiang.project.system.service.IUserService;
import com.wugenqiang.utils.MapCache;
import com.wugenqiang.utils.TaleUtils;
import com.wugenqiang.utils.UUID;
import com.wugenqiang.utils.ip.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 自定义拦截器
 * Created by BlueT on 2017/3/9.
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {
    private static final Logger LOGGE = LoggerFactory.getLogger(BaseInterceptor.class);
    private static final String USER_AGENT = "api-agent";

    @Resource
    private IUserService userService;

    private MapCache cache = MapCache.single();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();

        LOGGE.info("UserAgent: {}", request.getHeader(USER_AGENT));
        LOGGE.info("用户访问地址: {}, 来路地址: {}", uri, IPUtils.getIpAddrByRequest(request));


        //请求拦截处理
        User user = TaleUtils.getLoginUser(request);
        if (null == user) {
            Integer uid = TaleUtils.getCookieUid(request);
            if (null != uid) {
                //这里还是有安全隐患,cookie是可以伪造的
                user = userService.queryUserByUserId(uid);
                request.getSession().setAttribute(ParamConstant.LOGIN_SESSION_KEY, user);
            }
        }
        if (uri.startsWith("/lfd/admin") && !uri.startsWith("/lfd/admin/login") && null == user) {
            response.sendRedirect(request.getContextPath() + "/lfd/admin/login");
            return false;
        }
        //设置get请求的token
        if (request.getMethod().equals("GET")) {
            String csrf_token = UUID.UU64();
            // 默认存储30分钟
            cache.hset(Types.CSRF_TOKEN.getType(), csrf_token, uri, 30 * 60);
            request.setAttribute("_csrf_token", csrf_token);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
